﻿using System;
using System.Runtime.Serialization;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using ALDIOrganizer.Properties;

namespace ALDIOrganizer
{
    public partial class MainForm
    {
        void userAccountToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var ui = new UserAccountInfo();
            ui.ShowDialog();
        }

        void miFileImportTemplates_Click(object sender, EventArgs e)
        {
            if (!IsUserOKWithLeavingCurrentTemplate())
            {
                return;
            }
            string _where_from = String.Empty;
            if (Program.ShowImportTemplatesDialog(
                Path.GetFullPath(Program.CurrentFile.FileName)) ==
                DialogResult.OK)
            {
                _where_from = Program.GetSelectedFileName;
            }
            else
            {
                return;
            }            
            Program.CurrentFile.ImportTemplates(_where_from,
                GetFinalList);
            ChangeTemplate(CurrentTemplate.Name); // reloading current template in case if we overwrotei t with

            /*
             * Ask, which file from. Check if the file is not the one we've got Open :)
             * Initial directory - of the one we've got Open!
             * (Where are those variables?? check).
             * try to Open. then get the list of templates and ask which ones to import.
             * then check for duplicates, and ask which duplicates to overwrite, which ones drop.
             * then you have both lists 
             * DELEGATE!!
             * 
             * then import and pray it works fine!!
             * 
             * also it should ask automatically When you new file create.
             */
        }

        static List<string> GetFinalList(
            List<string> pAllTemplates,
            List<string> pDuplicateTemplates)
        {
            var chooseTemplates = new SelectTemplates(
                Resources.FORM_SelectTemplates_Title,
                Resources.FORM_SelectTemplates_Caption,
                pAllTemplates,
                false);
            if (chooseTemplates.ShowDialog() == DialogResult.OK)
            {
                var choice = chooseTemplates.GetUserChoice;
                var duplicates = (from template in choice
                                  where pDuplicateTemplates.Contains(template)
                                  select template).ToList();
                if (duplicates.Count == 0)
                {
                    return choice;
                }
                var pickDuplicatesToOverwrite = new SelectTemplates(
                    Resources.FORM_SelectTemplates_Title_Duplicates,
                    Resources.FORM_SelectTemplates_Caption_Duplicates,
                    duplicates,
                    false);
                if (pickDuplicatesToOverwrite.ShowDialog() == DialogResult.OK)
                {
                    var acceptedDuplicates = pickDuplicatesToOverwrite.GetUserChoice;
                    return (from template in choice
                            where !duplicates.Contains(template) ||
                            acceptedDuplicates.Contains(template)
                            select template).ToList();
                }
                return null; // user clicked Cancel in second dialog form
            }            
            return null; // user clicked Cancel in first dialog form
        }

        void openAnotherToolStripMenuItem_Click(object sender, EventArgs e)
        {
            // leaving...
            PromptAndLoadFiles(new OpenFileFormMode(OpenFileMode.OnlyOpenExisting,
                OpenFileMode.CreateOrOpen));
        }

        public void PopulateMRUInMainMenu()
        {
            miRecentlyOpen.Enabled =
                (Program.MRURotasFiles.GetList.Count != 0);            
            miRecentlyOpen.DropDownItems.Clear();            
            var _index = 0;
            foreach (var _entry in Program.MRURotasFiles.GetList)
            {
                var _item = new ToolStripMenuItem(
                    String.Concat(
                    (++_index).ToString(),
                    ". ",
                    _entry),
                    null, // image (we don't provide one)
                    new EventHandler(openRecentFile_Click)) {Tag = _entry};
                miRecentlyOpen.DropDownItems.Add(_item);
            }
            if (_index == 0)
            {
                return;
            }

            if (!Program.Logged.CanSaveDatafiles)
            {
                return;
            }            

            // TODO: AddAnotherRowString a string resource
            #region separator and "clear list"
            var _separator = new ToolStripSeparator();
            miRecentlyOpen.DropDownItems.Add(_separator);
            var _clear = new ToolStripMenuItem(
                "Clear",
                null, // image (we don't provide one)
                new EventHandler(clearMRUList_Click));
            miRecentlyOpen.DropDownItems.Add(_clear);
            #endregion
        }

        void clearMRUList_Click(object sender, EventArgs e)
        {
            Program.MRURotasFiles.ClearList(true);            
        }

        void openRecentFile_Click(object sender, EventArgs e)
        {
            var _me = sender as ToolStripMenuItem;
            if (_me == null)
            {
                return;
            }
            var _tag = _me.Tag as string;
            if (_tag == null)
            {
                return;
            }
            OpenFile(_tag);
        }

        void createnewToolStripMenuItem_Click(object sender, EventArgs e)
        {
            PromptAndLoadFiles(
                new OpenFileFormMode(OpenFileMode.OnlyCreateNew,
                OpenFileMode.OnlyCreateNew));
            SwitchToTab(tpStaff);            
        }

        void logOutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Relog();
        }

        void playsoundsToolStripMenuItem_Click(object sender, EventArgs e)
        {            
            Program.PlaySounds = !Program.PlaySounds;
            miOptionsPlaySounds.Checked = Program.PlaySounds;
        }

        void saveasToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (Program.ShowRotaSaveAsDialog(Path.GetFullPath(Program.CurrentFile.FileName)) !=
                DialogResult.OK)
            {
                return;
            }
            Hourglass(true);
            SaveFileAs(Program.GetSelectedFileName);
            Program.CurrentFile.FileName = Program.GetSelectedFileName;
            Program.MRURotasFiles.AddEntry(Program.CurrentFile.FileName, false, true);                
            UpdateTitlebar();
            Program.CurrentFile.Modified = false;
            Hourglass(false);
        }

        void saveToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Hourglass(true);
            SaveFile();
            Program.CurrentFile.Modified = false;
            Program.MRURotasFiles.AddEntry(Program.CurrentFile.FileName, false, true);            
            Hourglass(false);
        }

        void OpenFile(string pFileName)
        {   
            if(!Program.CurrentFile.OKLeaving())
            {
                return;
            }
            var _import_from = String.Empty;
            var _creating_new = !File.Exists(pFileName);
            if (_creating_new)
            {
                Program.formImportTemplates = new ImportTemplates();
                if (Program.formImportTemplates.ShowDialog() == DialogResult.OK)
                {
                    _import_from = Program.formImportTemplates.ImportFrom;
                }
                else
                {
                    return;
                }
                if (_creating_new)
                {
                    Program.CreateDatabase(
                            pFileName,
                            (DateTime?)null,
                            _import_from,
                            (_import_from != String.Empty) ? new DataFile.CopyThose(GetFinalList) : null);
                }
            }
            var exception = Program.ReadDatabase(pFileName);
            if (exception != null)
            {
                if( exception.GetType() == typeof (SerializationException))
                {
                    ErrorNoticeInvalidDataFileFormat();
                    return;
                }
                // Debugger.Break(); // unknown exception
                return;
            }
            // we carry on however, because SOME file is open
            svRota.DeactivateEvents();
            svTemplate.DeactivateEvents();
            CurrentTemplate = null;
            CurrentRota = null;
            // TODO: niech pyta czy opuszzac
            Hourglass(true);
            
            cbTemplate.Tag = true;
            LoadDefaultRota();
            CurrentFile_OnRotasCollectionModified();
            CurrentFile_OnTemplatesCollectionModified();
            CURRENTFILE_SetEventHandlers();
            cbTemplate.Tag = false;
            Program.MRURotasFiles.AddEntry(pFileName, false, true);            
            UpdateTitlebar();
            Program.CurrentFile.Modified = false;
            Sounds.Play(Sounds.Validated); 
            Hourglass(false);
        }

        void openToolStripMenuItem_Click(object sender, EventArgs e)
        {            
            if (Program.ShowRotaOpenDialog(String.Empty) == DialogResult.OK)
            {
                OpenFile(Program.GetSelectedFileName);                
            }
        }

        void Exit_Click(object sender, EventArgs e)
        {
            Quit();
        }

        void HelpAbout_Click(object sender, EventArgs e)
        {
            Program.aboutForm = new formAboutProgram();
            Program.aboutForm.ShowDialog();
        }


        void FileNew_Click(object sender, EventArgs e)
        {            
            Program.OpenFilesForm = new OpenFiles(
                String.Empty,
                String.Empty,
                new OpenFileFormMode(
                    OpenFileMode.ChoiceDisabled,
                    OpenFileMode.OnlyCreateNew));

            if (Program.OpenFilesForm.ShowDialog() == DialogResult.OK)
            {
                OpenFile(Program.OpenFilesForm.GetRotasTemplatesChoice);                
            }

        }
    }
}
